<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="160px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="排序" prop="orderNum">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.orderNum"-->
      <!--          placeholder="请输入排序"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
<!--      <el-form-item label="Splitting Device Fields" prop="deviceColum">-->
<!--        <el-input-->
<!--          v-model="queryParams.deviceColum"-->
<!--          placeholder="Splitting Device Fields"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:category:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:category:edit']"
        >编辑
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:category:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:category:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id" width="90"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="排序" align="center" prop="orderNum" width="110"/>
<!--      <el-table-column label="Splitting Device Fields" align="center" prop="deviceColum" width="160"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate('detail', scope.row)"
            v-hasPermi="['system:category:edit']"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleUpdate('copy', scope.row)"
            v-hasPermi="['system:category:edit']"
          >复制
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="cateId=scope.row.id,cateVisible=true"
            v-hasPermi="['system:category:remove']"
          >基本规则
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="cateId=scope.row.id,buttonVisible=true"
            v-hasPermi="['system:category:remove']"
          >基本操作
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:category:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或edit设备分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <div style="height: 500px;overflow-y: auto;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="Category Name"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="orderNum">
                <el-input v-model="form.orderNum" placeholder="Sort"/>
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item label="切分字段" prop="deviceColum">-->
<!--                <el-input v-model="form.deviceColum" placeholder="请输入切分设备的字段"/>-->
<!--                接收mqtt具体数据-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="参数名" prop="paramName">
                <el-input v-model="form.paramName" placeholder="参数名"/>
                接收mqtt数据中具体位置
<!--                Specific location in receiving mqtt data-->
              </el-form-item>
            </el-col>
            <el-col :span="24" class="mb10">
            <el-alert
              title="常规变量被包裹在{}中，单个变量如下：type/{deviceId}/up。"
              type="warning"
              :closable="false">
            </el-alert>
            </el-col>
            <el-col :span="12">
              <el-form-item label="推送规则" prop="pushTopic">
                <el-input v-model="form.pushTopic" placeholder="推送规则"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="接收规则" prop="subTopic">
                <el-input v-model="form.subTopic" placeholder="接收规则"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider content-position="center">类别数据配置信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCategoryDataConfig">新增
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteCategoryDataConfig">delete-->
          <!--            </el-button>-->
          <!--          </el-col>-->
        </el-row>
        <div v-for="(item, index) in downData" :key="index">
          <el-divider content-position="center">
            {{ index + 1 }} <i class="el-icon-remove-outline detel-line-index"
                               @click="handleDeleteCategoryDataConfig(index)"></i>
          </el-divider>
          <el-form label-width="90px">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="属性名">
                  <el-input v-model="item.name" placeholder="Attribute Name"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="属性类型">
                  <el-select v-model="item.keyType" placeholder="属性类型" style="width: 100%">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="item.keyType=='number'">
                <el-form-item label="属性单位">
                  <el-input v-model="item.unit" placeholder="属性单位"/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="item.keyType=='number' || item.keyType=='text'">
                <el-form-item label="默认值">
                  <el-input v-model="item.default_value" placeholder="默认值"/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="item.keyType=='number'">
                <el-form-item label="最大值">
                  <el-input v-model="item.max" placeholder="最大值"/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="item.keyType=='number'">
                <el-form-item label="最小值">
                  <el-input v-model="item.min" placeholder="最小值"/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="item.keyType=='switch'">
                <el-form-item label="开关类型">
                  <el-select v-model="item.type" placeholder="开关类型" style="width: 100%">
                    <el-option
                      v-for="item in selectvalue"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="item.keyType=='switch'">
                <el-form-item :label="switchName(0, index)">
                  <el-input v-model="item.true" placeholder="对应名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="item.keyType=='switch'">
                <el-form-item :label="switchName(1, index)">
                  <el-input v-model="item.false" placeholder="对应名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="描述">
                  <el-input v-model="item.remark" placeholder="描述"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!--        <el-table :data="categoryDataConfigList" :row-class-name="rowCategoryDataConfigIndex"-->
        <!--                  @selection-change="handleCategoryDataConfigSelectionChange" ref="categoryDataConfig">-->
        <!--          <el-table-column type="selection" width="50" align="center"/>-->
        <!--          <el-table-column label="序号" align="center" prop="index" width="50"/>-->
        <!--          <el-table-column label="字段" prop="columnName" width="150">-->
        <!--            <template slot-scope="scope">-->
        <!--              <el-input v-model="scope.row.columnName" placeholder="请输入字段"/>-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--          <el-table-column label="类型" prop="columnName" width="150">-->
        <!--            <template slot-scope="scope">-->
        <!--              <el-select v-model="value" placeholder="请选择">-->
        <!--                <el-option-->
        <!--                  v-for="item in options"-->
        <!--                  :key="item.value"-->
        <!--                  :label="item.label"-->
        <!--                  :value="item.value"-->
        <!--                  :disabled="item.disabled">-->
        <!--                </el-option>-->
        <!--              </el-select>-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--          <el-table-column label="说明" prop="comment">-->
        <!--            <template slot-scope="scope">-->
        <!--              <el-input v-model="scope.row.comment" placeholder="请输入说明"/>-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--        </el-table>-->
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">confirm</el-button>
        <el-button @click="cancel">cancel</el-button>
      </div>
    </el-dialog>
    <ruleList :cateId="cateId" :visible.sync="cateVisible"></ruleList>
    <buttonLine :cateId="cateId" :visible.sync="buttonVisible"></buttonLine>
  </div>
</template>

<script>
import {listCategory, getCategory, delCategory, addCategory, updateCategory} from "@/api/system/category";
import ruleList from "./ruleList";
import buttonLine from "./buttonLine";

export default {
  name: "Category",
  components:{ruleList, buttonLine},
  data() {
    return {
      // 遮罩层
      loading: true,
      buttonVisible: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCategoryDataConfig: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示search条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备分类表格数据
      categoryList: [],
      // 类别数据配置表格数据
      categoryDataConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      cateVisible: false,
      cateId: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        orderNum: null,
        deviceColum: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "Classification name cannot be empty", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "Creation time cannot be empty", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "Sort cannot be empty", trigger: "blur"}
        ],
      },
      options: [{
        value: 'switch',
        label: 'Switch'
      }, {
        value: 'number',
        label: 'Number',
      }, {
        value: 'text',
        label: 'String'
      }],
      selectvalue: [
        {
          value: 'true/flase',
          label: 'true/flase'
        },
        {
          value: '1/0',
          label: '1/0'
        },
        {
          value: 'ON/OF',
          label: '开/关'
        },
      ],
      value: '',
      downData: [],
      editType: ''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备分类列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // cancel按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单reset
    reset() {
      this.form = {
        id: null,
        name: null,
        createTime: null,
        orderNum: null,
        deviceColum: null,
        pushTopic:'',
        subTopic:'',
        paramName: ''
      };
      this.categoryDataConfigList = [];
      this.downData = []
      this.resetForm("form");
    },
    /** search按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** reset按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** add按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "Equipment classification";
    },
    /** edit按钮操作 */
    handleUpdate(type, row) {
      this.editType = type
      this.reset();
      const id = row.id || this.ids
      getCategory(id).then(response => {
        this.form = response.data;
        this.categoryDataConfigList = response.data.categoryDataConfigList;
        if (response.data.categoryDataConfigList && !response.data.downData) {
          for (let item of response.data.categoryDataConfigList) {
            this.downData.push({name: item.columnName, remark: item.comment})
          }
        }
        if (response.data.downData) {
          this.downData = JSON.parse(response.data.downData)
        }
        this.open = true;
        this.title = "edit设备分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let data_ = JSON.parse(JSON.stringify(this.form))
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.categoryDataConfigList = this.categoryDataConfigList;
          data_.downData = JSON.stringify(this.downData)
          if(this.editType==='copy'){
            delete data_.id
            addCategory(data_).then(response => {
              this.$modal.msgSuccess("复制成功");
              this.open = false;
              this.getList();
            });
          }else{
            if (data_.id != null) {
              updateCategory(data_).then(response => {
                this.$modal.msgSuccess("edit成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCategory(data_).then(response => {
                this.$modal.msgSuccess("add成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** delete按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('Are you sure to delete the data item for rule '+ids+'？').then(function () {
        return delCategory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("delete成功");
      }).catch(() => {
      });
    },
    /** 类别数据配置序号 */
    rowCategoryDataConfigIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 类别数据配置添加按钮操作 */
    handleAddCategoryDataConfig() {
      this.downData.push({})
      // let obj = {};
      // obj.key = "";
      // obj.comment = "";
      // this.categoryDataConfigList.push(obj);
    },
    /** 类别数据配置delete按钮操作 */
    handleDeleteCategoryDataConfig(index) {
      this.downData.splice(index, 1)
      // if (this.checkedCategoryDataConfig.length == 0) {
      //   this.$modal.msgError("请先选择要delete的类别数据配置数据");
      // } else {
      //   const categoryDataConfigList = this.categoryDataConfigList;
      //   const checkedCategoryDataConfig = this.checkedCategoryDataConfig;
      //   this.categoryDataConfigList = categoryDataConfigList.filter(function (item) {
      //     return checkedCategoryDataConfig.indexOf(item.index) == -1
      //   });
      // }
    },
    /** 复选框选中数据 */
    handleCategoryDataConfigSelectionChange(selection) {
      this.checkedCategoryDataConfig = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/category/export', {
        ...this.queryParams
      }, `category_${new Date().getTime()}.xlsx`)
    },
    switchName(type, index) {
      // item.keyType=='switch' item.type
      if (this.downData[index].keyType === 'switch' && this.downData[index].type) {
        console.log('downData:', this.downData[index])
        let type_ = this.downData[index].type.split('/')
        return `【${type_[type]}】名称`
      } else {
        return 'Corresponding name'
      }
    },
  }
};
</script>
<style>
.detel-line-index {
  color: #ed5565;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
}
</style>
